"""
word 替换  电脑需要提前安装office
"""
import os
from win32com import client
import chardet


def get_encoding(file):
    with open(file, 'rb') as f:
        return chardet.detect(f.read())['encoding']


def get_replace_dict():
    repl = dict()
    path = os.getcwd()
    filename_list = os.listdir(path)
    txt = [
        filename for filename in filename_list if filename.endswith(".txt")]
    encoding = get_encoding(txt[0])
    try:
        file = open(txt[0], encoding=encoding, mode="r")
        lines = file.readlines()
        for line in lines:
            line_str = line.strip()
            split = line_str.split(';')
            repl[split[0]] = split[1]
        file.close()
        return repl
    except IOError as ioe:
        print("替换.txt 不存在")
    except:
        print("请检查替换.txt格式是否正确：每行应为<需要被替换的值>；<新的值>")


def get_path():
    path = os.getcwd()
    filename_list = os.listdir(path)

    wordname_list = [
        filename for filename in filename_list if filename.endswith((".doc", ".docx"))]

    for wordname in wordname_list:
        wordpath = os.path.join(path, wordname)
        # yield 生成器
        yield wordpath


def replace(repl_dict, wordpath):
    word = client.Dispatch("Word.Application")
    word.Visible = 0
    word.DisplayAlerts = 0
    doc = word.Documents.Open(wordpath)
    for key, value in repl_dict.items():
        word.Selection.Find.ClearFormatting()
        word.Selection.Find.Replacement.ClearFormatting()
        # ------------------------------------------------------
        # 此函数设计到可能出现的各种情况，请酌情修改
        # Execute(
        #         旧字符串，表示要进行替换的字符串
        #         区分大小写：这个好理解，就是大小写对其也有影响
        #         完全匹配：也就意味着不会替换单词中部分符合的内容
        #         使用通配符
        #         同等音
        #         包括单词的所有形态
        #         倒序
        #         1（不清楚是做什么的）
        #         包含格式
        #         新的文本
        #         要替换的数量，0表示不进行替换，1表示仅替换一个 2-全部替换
        # ------------------------------------------------------
        word.Selection.Find.Execute(key, False, False, False, False, False, True, 1, True, value, 2)
    doc.Save()
    doc.Close()


def replace_word():
    repl_dict = get_replace_dict()
    for wordpath in get_path():
        print(">>:", wordpath, "开始替换...")
        replace(repl_dict, wordpath)
        print(">>:", wordpath, "替换完成")


if __name__ == "__main__":
    replace_word()
